<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Croakd
 * Account controller
 * @author     hypn
 */
class Account_Controller extends Core_Controller {

	public function index() {
	}
	
	public function signup() {
		// Token from twitter
		$twitter_link		= '';
		$twitter_oauth	= new TwitterOAuth(Kohana::config('app.twitter_consumer_key'), Kohana::config('app.twitter_consumer_secret'));
		$request_token	= $twitter_oauth->getRequestToken();
		if (isset($request_token)) {
			$this->session->set('oauth_request_token', $request_token['oauth_token']);
			$this->session->set('oauth_request_token_secret', $request_token['oauth_token_secret']);
		
			// Token link		
			$twitter_link = $twitter_oauth->getAuthenticateURL($this->session->get('oauth_request_token'));
		}
		else {
			$twitter_link = "/";
		}
		url::redirect($twitter_link);
	}

	public function oauth()
	{
		if ($oauth_token = $this->input->get('oauth_token')) {
			$twitter_oauth	= new TwitterOAuth(Kohana::config('app.twitter_consumer_key'), Kohana::config('app.twitter_consumer_secret'), $this->session->get('oauth_request_token'), $this->session->get('oauth_request_token_secret'));
			$access_token	= $twitter_oauth->getAccessToken();
			$twitter_oauth	= new TwitterOAuth(Kohana::config('app.twitter_consumer_key'), Kohana::config('app.twitter_consumer_secret'), $access_token['oauth_token'], $access_token['oauth_token_secret']);
			$credentials	= $twitter_oauth->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
			$user_info		= simplexml_load_string($credentials);
			if (ORM::factory('user')->username_exists((string)$user_info->screen_name) == TRUE) {
				$this->auth->force_login((string)$user_info->screen_name);
				url::redirect('/triggers');
			}
			else {
				// Registro el usuario
				$data['username']						= (string)$user_info->screen_name;
				$data['email']							= (string)$user_info->screen_name."@";
				$data['password']						= substr($this->auth->hash_password((string)$user_info->screen_name),6);
		    $data['name']								= (string)$user_info->name;
				$data['profile_image_url']	= (string)$user_info->profile_image_url;
		    $data['created_at']					= date('Y-m-d H:i:s');
		    $user_id										= ORM::factory('user')->create($data);
			    
		    if ($user_id !== FALSE) {
					$this->auth->force_login("$user_info->screen_name");
				}
				
				// Registro los access de twitter
				$access['user_id']				= $user_id;
				$access['access_token']		= (string)$access_token['oauth_token'];
				$access['access_secret']	= (string)$access_token['oauth_token_secret'];
				$access['created']				= date('Y-m-d H:i:s');
				ORM::factory('twitter_access')->create($access);

				url::redirect('/trigger');
			}
		}
		url::redirect('/');
	}
	
	public function logout()
	{
		$this->auth->logout();
		url::redirect('/');
	}
	
}
